package com.jdk.learn.juc._08lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by ricky
 * on 2018/2/1.
 */
public class _08ReadWriteLock {
    public static void main(String[] args) {
        ReadWriteLockDemo rw=new ReadWriteLockDemo();
        new Thread(()->{
            rw.write((int) (Math.random()*100));
        },"write").start();

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                rw.read();
            },"read").start();
        }

    }

}

class ReadWriteLockDemo {

    private  int num=1;//线程号
    private ReadWriteLock readWrite=new ReentrantReadWriteLock();
    private Lock read=readWrite.readLock();
    private Lock wirte=readWrite.writeLock();


    /**
     * 读锁  可以多个读线程同时读
     */
    public void read(){
        read.lock();
        try {
            System.out.println(Thread.currentThread().getName()+":"+num);
        }finally {
            read.unlock();
        }
    }

    /**
     * 写锁 独占锁  与读互斥 写互斥
     */
    public void write(int nums){
        wirte.lock();
        try {
            this.num=nums;
            System.out.println(Thread.currentThread().getName()+":"+nums);
        }finally {
            wirte.unlock();
        }
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
}
